<template>
  <div class="rabattBox sub-main">
    <!-- 根据路由传参type 渲染店铺 -->
    <ActivitySlot class="activityRabatt" :imgTitle="imgTitle">
      <!-- 顶部标题填充内容 -->
      <template #title>
        <div
          class="title"
          v-if="flag&&$route.query.shopId || !$route.query.shopId"
        >
          <span
            class="glodTxt"
            v-if="$route.query.shopId && !ifPreheat"
          >活动结束倒计时</span>
          <span
            class="glodTxt"
            v-if="$route.query.shopId && ifPreheat"
          >活动开始倒计时</span>
          <span
            class="glodTxt"
            v-if="!$route.query.shopId && sessionList[idInx] && sessionList[idInx].type === 1"
          >{{ sessionList[idInx].startTime }} 场结束倒计时</span>
          <span
            class="glodTxt"
            v-if="!$route.query.shopId && sessionList[idInx] && !sessionList[idInx].type"
          >{{ sessionList[idInx].startTime }} 场开始倒计时</span>
          <div class="timeBox">
            <div class="hour bc">{{ formatHours(time) }}</div>
            <div class="after">:</div>
            <div class="min bc">{{ formatMinutes(time) }}</div>
            <div class="after">:</div>
            <div class="sec bc">{{ formatSeconds(time) }}</div>
          </div>
        </div>
      </template>
      <template #section>
        <div
          class="timeList"
          v-if="!$route.query.shopId"
          :class="sessionList.length>4?'long':''"
        >
          <div
            class="time"
            :class="index===idInx?'start':''"
            v-for="(item,index) in sessionList"
            :key="index"
            @click="changeSession(index)"
          >
            {{ item.startTime }}&emsp;{{ item.type === 1 ? '抢购中':item.type === 2?'已结束':'未开始' }}
          </div>
        </div>
        <div class="rabattList" v-if="flag" v-loading="loadingList">
          <div
            class="item"
            v-for="item in proList"
            :key="item.productId"
          >
            <ItemSlot
              :data="item"
              @toDetail="toProductDetail(item)"
            >
              <template #extra v-if="item.limitStockNumber">
                <div class="progress">
                  <span>限量{{ item.limitStockNumber }}件</span>
                  <el-progress
                    :color="'#C83732'"
                    :show-text="false"
                    :stroke-width="26"
                    :percentage="(item.limitStockNumber / item.limitNumber) * 100" />
                </div>
              </template>
              <template #icon>
                <svg-icon
                  style="width: 57px;height: 57px;"
                  name="activity-miaosha"
                />
              </template>
              <template #button v-if="sessionList.length">
                <button
                  class="buy"
                  :class="sessionList[idInx].type === 1 ? 'butNow' : sessionList[idInx].type === 2 ? 'buyNot' : 'buyWill'"
                  @click="toProductDetail(item)"
                >{{ sessionList[idInx].type === 1 ? '立即抢购' : sessionList[idInx].type === 2 ? '已结束' : '未开始' }}</button>
              </template>
              <template #button v-else>
                <button
                  class="buy"
                  :class="ifPreheat ? 'buyWill' : 'butNow'"
                  @click="toProductDetail(item)"
                >{{ ifPreheat ? '未开始' : '立即抢购' }}</button>
              </template>
            </ItemSlot>
          </div>
        </div>
        <div v-else class="noproduct">
          <svg-icon style="width: 240px; height: 240px; margin-bottom: 20px;" name="user-order-nodata" />
          <p class="fs20 font-color-999">该活动没有商品～</p>
        </div>
      </template>
    </ActivitySlot>
    <el-pagination
      v-if="flag"
      style="margin-bottom:20px;"
      background
      layout="prev, pager, next, jumper"
      :page-size="pageSize"
      :current-page="page"
      @current-change="changePage"
      :total="total" />
  </div>
</template>

<script setup>
import ActivitySlot from '@/components/activity/activitySlot.vue'
import ItemSlot from '@/views/promotions/components/itemSlot.vue'
import SvgIcon from '@/components/svgIcon/index.vue';
import {
  getSeckill,
  getSeckillIndex,
  getSeckillTime
} from '@/api/Activity/ActivitySeckill.js'
import { defineComponent, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

defineComponent({
  name:'Rabatt'
})

const imgTitle = ref('static/image/activity/rabattTitle.webp')
const page = ref(1)
const pageSize = ref(12)
const total = ref(0)
const ids = ref('')
const shopId = ref('')
const proList = ref([])
const loadingList = ref(false)
const time = ref('')
const setTime = ref(null)
const limitNumber = ref(null)
const ifPreheat = ref(false)
const type=ref('')
const volume = ref('')
const index = ref('1')
const flag = ref(true)
const idInx = ref(0)
const sessionList = ref([])

function formatHours (value) {
  let hours = Math.floor(value / (1000 * 60 * 60))
  if (hours < 10 && hours > 0) {
    return '0' + hours
  } else if (hours > 10) {
    return hours
  } else {
    return '00'
  }
}

function formatMinutes (value) {
  let minutes = Math.floor((value % (1000 * 60 * 60)) / (1000 * 60))
  if (minutes < 10 && minutes > 0) {
    return '0' + minutes
  } else if (minutes > 10) {
    return minutes
  } else {
    return '00'
  }
}

function formatSeconds (value) {
  let seconds = Math.round((value % (1000 * 60)) / 1000)
  if (seconds < 10 && seconds > 0) {
    return '0' + seconds
  } else if (seconds > 10) {
    return seconds
  } else {
    return '00'
  }
}

const route = useRoute()

onMounted(()=>{
  if (route.query.ids) {
    ids.value = route.query.ids
  }
  if (route.query.shopId) {
    shopId.value = route.query.shopId
    handleGetSeckill()
  } else {
    getSeckills()
  }
})

onBeforeUnmount (()=>{
  clearInterval(setTime)
})

// 倒计时
function countDown () {
  clearInterval(setTime.value)
  setTime.value = setInterval(() => {
    if (time.value < 1000) {
      clearInterval(setTime.value)
      // return alert('活动已结束')
      return
    }
    time.value -= 1000
  }, 1000)
}

const router = useRouter()
// 跳转到商品详情
function toProductDetail (item) {
  let data = {
    productId: item.productId,
    shopId: item.shopId,
    skuId: item.skuId
  }
  router.push({
    path: '/productDetail',
    query: {
      proData: JSON.stringify(data)
    }
  })
}

// 获取平台秒杀专区列表
async function getPlatformSeckills () {
  if (!sessionList.value[idInx.value]) {
    flag.value = false
    return
  }
  const response = await getSeckill({
    page: page.value,
    pageSize: pageSize.value,
    session: sessionList.value[idInx.value].startTime
  })
  const res = response.data
  if (res.code === '200') {
    proList.value = res.data.list
    total.value = parseInt(res.data.total)
    if (res.data.list.length) {
      flag.value = true
    } else {
      flag.value = false
    }
  }
}

// 获取秒杀专区列表
async function handleGetSeckill () {
  loadingList.value = true
  let params = {
    shopId: shopId.value,
    shopSeckillId: ids.value[0] || ids.value,
    page: page.value,
    pageSize: pageSize.value
  }
  if (ids.value === '') {
    params.volume = volume.value
    params.type = type.value
  }
  const response = await getSeckillIndex(params)
  const res = response.data
  if (res.code === '200') {
    ifPreheat.value = res.data.state !== 1
    proList.value = res.data.page.list
    total.value = res.data.page.total
    time.value = ifPreheat.value ? res.data.enableTime : res.data.time
    limitNumber.value = res.data.limitNumber
    if (res.data.page.list.length) {
      flag.value = true
    } else {
      flag.value = false
      time.value = 0
    }
    if (ids.value !== '' && flag.value) {
      countDown()
    }
    // shopName = res.data.shopName
    // shopLogo = res.data.shopLogo
  } else {
    ElMessage.warning(res.message)
  }
  loadingList.value = false
}

// 切换活动
function changeSession (index) {
  idInx.value = index
  page.value = 1
  if (sessionList.value[idInx.value]?.type === 1) { // 抢购中
    time.value = new Date(sessionList.value[idInx.value].endTime).getTime() - new Date().getTime()
  }
  if (!sessionList[idInx.value]?.type) { // 未开始
    time.value = new Date(sessionList.value[idInx.value].startTime).getTime() - new Date().getTime()
  }
  if (time.value > 0) {
    countDown()
  } else {
    time.value = 0
  }
  getPlatformSeckills()
}

// 获取活动时间段
async function getSeckills () {
  const response = await getSeckillTime()
  const res = response.data
  if (res.code === '200') {
    // type: 0 未开始    1抢购中   2已结束
    sessionList.value = res.data.map(item => {
      const [startTime, endTime] = item.split('|')
      let timesStart = new Date(startTime).getTime() - new Date().getTime() > 0 ? 0 : 1
      let timesEnd = new Date(endTime).getTime() - new Date().getTime() > 0 ? 0 : 1
      return {
        startTime,
        endTime,
        type: timesStart && !timesEnd ? 1 : timesStart && timesEnd ? 2 : 0
      }
    })
    if (sessionList.value[idInx.value] && sessionList.value[idInx.value].type === 1) { // 抢购中
      time.value = new Date(sessionList.value[idInx.value].endTime).getTime() - new Date().getTime()
    }
    if (sessionList.value[idInx.value] && !sessionList.value[idInx.value].type) { // 未开始
      time.value = new Date(sessionList.value[idInx.value].startTime).getTime() - new Date().getTime()
    }
    if (time.value > 0) {
      countDown()
    } else {
      time.value = 0
    }
    getPlatformSeckills()
  } else {
    ElMessage.warning(res.message)
  }
}

// 翻页
function changePage (val) {
  page.value = val
  handleGetSeckill()
}

// 默认
function defaultSort () {
  index.value = '1'
  page.value = 1
  type.value = ''
  volume.value = ''
  handleGetSeckill()
}

// 价格
function priceSort () {
  index.value = '2'
  page.value = 1
  if (type.value === '' || type.value === 2) {
    type.value = 1
  } else {
    type.value = 2
  }
  volume.value = ''
  handleGetSeckill()
}

// 销量
function salesSort () {
  index.value = '3'
  page.value = 1
  if (volume.value === '' || volume.value === 2) {
    volume.value = 1
  } else {
    volume.value = 2
  }
  type.value = ''
  handleGetSeckill()
}

</script>

<style lang="scss" scoped>
.rabattBox {
  max-width: 1250px;
  margin: auto;
  .activityRabatt{
    position: relative;
    .title{
      width: 40%;
      height: 60px;
      color: #FFF;
      margin: auto;
      text-align: center;
      position: absolute;
      top: 160px;
      left: 0;
      right: 0;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .glodTxt{
        color: #FFEBC4;
        font-size: 16px;
      }
      .timeBox{
        height: 60px;
        display: flex;
        align-items: center;
        .after{
          font-size: 30px;
          margin: 0 13px;
        }
        .bc{
          width: 40px;
          height: 40px;
          line-height: 40px;
          font-size: 20px;
          color: #FFFFFF;
          background-color: #333333;
        }
      }
    }
    .timeList{
      // width: 1200px;
      height: 60px;
      margin-top: 20px;
      overflow-y: auto;
      display: flex;
      flex-wrap: nowrap;
      overflow-y: hidden;
      .time{
        flex: 0 0 23%;
        height: 60px;
        line-height: 60px;
        text-align: center;
        color: #999;
        margin: 0 1%;
        cursor: pointer;
        background-color: #E4E5E6;
      }
      .start{
        background-color: #333;
        color: #FFEBC4;
      }
    }
    .long{
      padding-bottom: 15px;
    }
    .rabattList {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      min-height: 532px;
      .item {
        width: 23%;
        margin: 20px 1%;
        transition: all 0.3s linear;
        .progress{
          width: 100%;
          height: 40px;
          background-color: #DADBDC;
          position: absolute;
          bottom: 0;
          display: flex;
          align-items: center;
          span{
            margin-left: 10px;
          }
          :deep(.el-progress){
            flex: 1;
            height: 10px;
            margin: 0 10px;
            // .el-progress-bar{
            //   height: 10px;
            // }
            .el-progress-bar__outer,.el-progress-bar__inner{
              border-radius: 0;
              height: 10px !important;
            }
          }
        }
        .buy{
          width: 100%;
          height: 40px;
          padding: 0;
          margin: 15px 0 0;
          color: #fff;
          cursor: pointer;
        }
        .butNow{
          background: linear-gradient(90deg, #C83732 0%, #E25C44 100%);
          box-shadow: 0px 3px 6px rgba(233, 0, 0, 0.3);
        }
        .buyNot{
          background-color: #999999;
        }
        .buyWill{
          background: linear-gradient(90deg, #29C790 0%, #75D98C 100%);
          box-shadow: 0px 3px 6px rgba(52, 203, 144, 0.3);
        }
      }
      .item:hover{
        box-shadow:0 0 20px #cccccc;
      }
    }
  }
  .noproduct{
    width: 100%;
    text-align: center;
    min-height: 500px;
    img{
      margin-top: 50px;
    }
  }
}
// 隐藏滚动条
// .timeList::-webkit-scrollbar {
//   display: none; /* Chrome Safari */
// }
// .timeList{
//   scrollbar-width: none; /* firefox */
//   -ms-overflow-style: none; /* IE 10+ */
// }
</style>
